package cn.kent.util;

import cn.hutool.core.io.IoUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author wuYuHua
 * @version 1.0.0
 * @ClassName Example.java
 * @Description 示例
 * @createTime 2022年09月13日 17:05:00
 */
public class Example {
    private static final String OUT = "F:\\Download\\test";
    private static final String FILE_ONE_PATH = "F:\\Download\\test\\1.txt";
    private static final String FILE_TWO_PATH = "F:\\Download\\test\\1.pdf";

    public static void main(String[] args) {
        List<File> files = new ArrayList<>();
        // 获取两个文件
        File fileOne = new File(FILE_ONE_PATH);
        File fileTwo = new File(FILE_TWO_PATH);
        files.add(fileOne);
        files.add(fileTwo);
        try {
            zipFile(files);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void zipFile(List<File> fileList) throws IOException {
        // 文件的压缩包路径
        String zipPath = OUT+"/"+System.currentTimeMillis()+".zip";
        // 获取文件压缩包输出流
        try (OutputStream outputStream = new FileOutputStream(zipPath);
             CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream,new Adler32());
             ZipOutputStream zipOut = new ZipOutputStream(checkedOutputStream)){
            for (File file : fileList) {
                // 获取文件输入流
                InputStream fileIn = new FileInputStream(file);
                byte[] bytes = IoUtil.readBytes(fileIn);
                // 写入数据并刷新
                zipOut.putNextEntry(new ZipEntry(file.getName()));
                zipOut.write(bytes,0,bytes.length);
                zipOut.flush();
                fileIn.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

